package cn.lili.modules.message.controller;

import cn.lili.common.utils.PageUtil;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.SearchVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.message.entity.ShortLink;
import cn.lili.modules.message.service.ShortLinkService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @author Chopper
 */
@RestController
@Api(tags = "短链接接口")
@RequestMapping("/lili/shortLink")
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ShortLinkController {

    private final ShortLinkService shortLinkService;

    @GetMapping(value = "/{id}")
    @ApiOperation(value = "查看短链接详情")
    public ResultMessage<ShortLink> get(@PathVariable String id){

        ShortLink shortLink = shortLinkService.getById(id);
        return new ResultUtil<ShortLink>().setData(shortLink);
    }

    @GetMapping
    @ApiOperation(value = "分页获取短链接")
    public ResultMessage<IPage<ShortLink>> getByPage(ShortLink entity,
                                                        SearchVO searchVo,
                                                        PageVO page){
        IPage<ShortLink> data = shortLinkService.page(PageUtil.initPage(page),PageUtil.initWrapper(entity, searchVo));
        return new ResultUtil<IPage<ShortLink>>().setData(data);
    }

    @PostMapping
    @ApiOperation(value = "新增短链接")
    public ResultMessage<ShortLink> save(ShortLink shortLink){

        if(shortLinkService.save(shortLink)){
            return new ResultUtil<ShortLink>().setData(shortLink);
        }
        return new ResultUtil<ShortLink>().setErrorMsg("未知异常，请稍后重试");
    }

    @PutMapping("/{id}")
    @ApiOperation(value = "更新短链接")
    public ResultMessage<ShortLink> update(@PathVariable String id, ShortLink shortLink){
        if(shortLinkService.updateById(shortLink)){
            return new ResultUtil<ShortLink>().setData(shortLink);
        }
        return new ResultUtil<ShortLink>().setErrorMsg("未知异常，请稍后重试");
    }

    @DeleteMapping(value = "/{ids}")
    @ApiOperation(value = "删除短链接")
    public ResultMessage<Object> delAllByIds(@PathVariable List ids){

        shortLinkService.removeByIds(ids);
        return ResultUtil.success("成功删除");
    }
}
